package com.warren.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.warren.auth.entity.JwtUser;
import com.warren.biz.entity.InStock;
import com.warren.biz.entity.InStockInfo;
import com.warren.biz.entity.ProductStock;
import com.warren.biz.mapper.InStockInfoMapper;
import com.warren.biz.mapper.InStockMapper;
import com.warren.biz.mapper.ProductStockMapper;
import com.warren.biz.service.InStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.warren.biz.vo.IntoStockVO;
import com.warren.handler.BusinessException;
import com.warren.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.net.BindException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author warren
 * @since 2021-04-20
 */
@Service
public class InStockServiceImpl extends ServiceImpl<InStockMapper, InStock> implements InStockService {

    @Resource
    private InStockInfoMapper inStockInfoMapper;

    @Resource
    private ProductStockMapper productStockMapper;

    @Override
    public IPage<InStock> findInStockList(Page<InStock> page, QueryWrapper<InStock> queryWrapper) {
        return baseMapper.findInStockList(page,queryWrapper);
    }

    @Override
    public void addIntoStock(IntoStockVO intoStockVO) {
        //随机生成入库单号
        String IN_STOCK_NUM = UUID.randomUUID().toString().substring(0,32);
        //记录该单的总数
        int itemNumber = 0;
        List<InStockInfo> products = intoStockVO.getProducts();
        //添加入库明细
        if (!ObjectUtils.isEmpty(products)){
            for (InStockInfo product : products){
                itemNumber += product.getProductNumber();
                product.setInNum(IN_STOCK_NUM);
                inStockInfoMapper.insert(product);
            }
        }

        InStock inStock = new InStock();
        inStock.setInNum(IN_STOCK_NUM);
        inStock.setProductNumber(itemNumber);

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)){
            JwtUser userInfo = (JwtUser) authentication.getPrincipal();
            inStock.setOperator(userInfo.getUsername());
        }

        if (intoStockVO.getSupplierId() != null){
            inStock.setSupplierId(intoStockVO.getSupplierId());
        }

        inStock.setStatus(2);
        inStock.setRemark(intoStockVO.getRemark());
        inStock.setType(intoStockVO.getType());
        this.baseMapper.insert(inStock);
    }

    @Override
    public void publishInStock(Long id, String inNum) {
        InStock inStock = new InStock();
        QueryWrapper<InStockInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("in_num",inNum);
        List<InStockInfo> inStockInfos = inStockInfoMapper.selectList(queryWrapper);

        if (!ObjectUtils.isEmpty(inStockInfos)){
            for (InStockInfo inStockInfo : inStockInfos){
                //物资编号
                String pNum = inStockInfo.getPNum();
                //入库物资数
                Integer productNumber = inStockInfo.getProductNumber();
                QueryWrapper<ProductStock> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("p_num",pNum);
                //仓库物品
                ProductStock productStock = productStockMapper.selectOne(queryWrapper1);
                //仓库已有这个物品
                if (!ObjectUtils.isEmpty(productStock)){
                    productStock.setStock(productStock.getStock() + (long) productNumber);
                    productStockMapper.updateById(productStock);
                }else {
                    ProductStock productStock1 = new ProductStock();
                    productStock1.setPNum(pNum);
                    productStock1.setStock((long) productNumber);
                    productStockMapper.insert(productStock1);
                }
            }
            inStock.setId(id);
            inStock.setStatus(0);
            this.baseMapper.updateById(inStock);
        }
    }

    @Override
    public void delete(Long id, String inNum) {
        QueryWrapper<InStockInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("in_num",inNum);
        inStockInfoMapper.delete(queryWrapper);
        this.baseMapper.deleteById(id);
    }

    @Override
    public void remove(Long id) {
        InStock inStock = this.baseMapper.selectById(id);
        if (inStock == null){
            throw new BusinessException(ResultCode.PARAMETER_ERROR.getCode(),ResultCode.PARAMETER_ERROR.getMessage());
        }
        Integer status = inStock.getStatus();
        //只有status = 0 ,正常情况下，才可以移入回收站
        if (status != 0){
            throw new BusinessException(ResultCode.PARAMETER_STATUS_ERROR.getCode(), ResultCode.SUCCESS.getMessage());
        }else {
            InStock in = new InStock();
            in.setStatus(1);
            in.setId(id);
            this.baseMapper.updateById(in);
        }
    }

    @Override
    public void back(Long id) {
        InStock t = new InStock();
        t.setId(id);
        InStock inStock = this.baseMapper.selectById(t);
        if(inStock.getStatus() != 1){
            throw new BusinessException(ResultCode.PARAMETER_STATUS_ERROR.getCode(),ResultCode.PARAMETER_STATUS_ERROR.getMessage());
        }else{
            t.setStatus(0);
            this.baseMapper.updateById(t);
        }
    }


}
